import React, { useState } from 'react';
import { Key, Plus, Clock, Shield, RefreshCw } from 'lucide-react';

interface CryptoKey {
  id: string;
  content: string;
  createdAt: string;
  isActive: boolean;
  operator: string;
  expiryDate?: string;
}

export const KeyManagement: React.FC = () => {
  const [keys, setKeys] = useState<CryptoKey[]>([
    {
      id: 'K001',
      content: 'AE8F9B2C1D5E6A7B',
      createdAt: '2024-11-25 09:30:00',
      isActive: true,
      operator: '李管理员'
    },
    {
      id: 'K002',
      content: '3F7A8D9E2B4C5F1A',
      createdAt: '2024-11-20 14:15:00',
      isActive: false,
      operator: '李管理员',
      expiryDate: '2024-12-02'
    }
  ]);
  const [isGenerating, setIsGenerating] = useState(false);

  const generateNewKey = async () => {
    setIsGenerating(true);
    
    // Simulate key generation
    setTimeout(() => {
      const newKey: CryptoKey = {
        id: `K${(keys.length + 1).toString().padStart(3, '0')}`,
        content: Math.random().toString(36).substring(2, 18).toUpperCase(),
        createdAt: new Date().toLocaleString(),
        isActive: true,
        operator: '李管理员'
      };
      
      // Deactivate old keys
      const updatedKeys = keys.map(key => ({ ...key, isActive: false }));
      setKeys([newKey, ...updatedKeys]);
      setIsGenerating(false);
    }, 2000);
  };

  const formatKey = (key: string) => {
    return key.match(/.{1,4}/g)?.join('-') || key;
  };

  return (
    <div className="max-w-4xl mx-auto">
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm">
        <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white">密钥管理</h2>
              <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                管理系统加密密钥，确保二维码验证安全性
              </p>
            </div>
            <button
              onClick={generateNewKey}
              disabled={isGenerating}
              className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              {isGenerating ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                  生成中...
                </>
              ) : (
                <>
                  <Plus className="h-4 w-4 mr-2" />
                  生成新密钥
                </>
              )}
            </button>
          </div>
        </div>

        <div className="p-6">
          {/* Active key */}
          <div className="mb-6">
            <h3 className="text-md font-medium text-gray-900 dark:text-white mb-3">当前有效密钥</h3>
            {keys.find(key => key.isActive) ? (
              <div className="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-4">
                <div className="flex items-start justify-between">
                  <div className="flex items-center">
                    <Shield className="h-5 w-5 text-green-600 dark:text-green-400 mr-3" />
                    <div>
                      <p className="font-mono text-lg font-semibold text-gray-900 dark:text-white">
                        {formatKey(keys.find(key => key.isActive)!.content)}
                      </p>
                      <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                        创建时间：{keys.find(key => key.isActive)!.createdAt}
                      </p>
                      <p className="text-sm text-gray-600 dark:text-gray-400">
                        操作人员：{keys.find(key => key.isActive)!.operator}
                      </p>
                    </div>
                  </div>
                  <span className="px-3 py-1 text-sm bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200 rounded-full">
                    使用中
                  </span>
                </div>
              </div>
            ) : (
              <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
                <p className="text-yellow-800 dark:text-yellow-200">当前没有有效密钥，请生成新密钥</p>
              </div>
            )}
          </div>

          {/* Historical keys */}
          <div>
            <h3 className="text-md font-medium text-gray-900 dark:text-white mb-3">历史密钥记录</h3>
            <div className="space-y-3">
              {keys.filter(key => !key.isActive).map((key) => (
                <div key={key.id} className="bg-gray-50 dark:bg-gray-700 rounded-lg p-4">
                  <div className="flex items-start justify-between">
                    <div className="flex items-center">
                      <Key className="h-5 w-5 text-gray-400 mr-3" />
                      <div>
                        <p className="font-mono text-md font-medium text-gray-900 dark:text-white">
                          {formatKey(key.content)}
                        </p>
                        <div className="flex items-center text-sm text-gray-600 dark:text-gray-400 mt-1 space-x-4">
                          <div className="flex items-center">
                            <Clock className="h-3 w-3 mr-1" />
                            创建：{key.createdAt}
                          </div>
                          <span>操作人：{key.operator}</span>
                          {key.expiryDate && (
                            <span className="text-red-600 dark:text-red-400">
                              过期：{key.expiryDate}
                            </span>
                          )}
                        </div>
                      </div>
                    </div>
                    <span className="px-3 py-1 text-sm bg-gray-100 text-gray-600 dark:bg-gray-600 dark:text-gray-300 rounded-full">
                      已停用
                    </span>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Key management info */}
          <div className="mt-6 p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
            <h4 className="font-medium text-blue-900 dark:text-blue-200 mb-2">密钥管理说明</h4>
            <ul className="text-sm text-blue-800 dark:text-blue-300 space-y-1">
              <li>• 新生成的密钥将立即生效，用于后续的二维码验证</li>
              <li>• 旧密钥将保留7天，用于验证历史生成的二维码</li>
              <li>• 所有密钥操作都会记录在审计日志中</li>
              <li>• 建议定期更换密钥以确保系统安全性</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  );
};